// 数据统计路由
const statics = require('express').Router();
// 订单模型
const {
	Orders
} = require('../models/order');
// 商品模型
const {
	Goods
} = require('../models/good');
// 三级分类模型
const {
	CategoryThree
} = require('../models/category');
// 统一数据返回类
const {
	DataReturn
} = require('../common/returnclass');

function getCurrWeek() {
	var d = new Date();
	// 获取当前周的星期几
	var day = d.getDay();
	// 获取周一
	var week_begin = new Date(getFormatDate(day));

	return week_begin;
}


// 获取当周的周一
function getFormatDate(day) {
	var d = new Date();
	var minus = day ? day - 1 : 6;
	d.setDate(d.getDate() - minus); //获取minus天前的日期
	var year = d.getFullYear();
	var month = d.getMonth() + 1;
	var days = d.getDate();
	return year + "-" + formatDate(month) + "-" + formatDate(days);
}

//格式化月和日为MM、dd
function formatDate(value){
    if(value < 10){
        value = "0" + value;
    }
    return value;
}

function getCurrentMonthBegin() {
	var d = new Date();
	// 获取当前月的第一天
	var month_begin = new Date(d.setDate(1));
	return month_begin;
}

function getCurrentMonthEnd() {
	var d = new Date();
	// 获取当前月的最后一天
	var currentMonth = d.getMonth() + 1;
	d.setMonth(currentMonth);
	d.setDate(0);
	return d.getDate();
}

/**
 * @api {Get} /statics 获取商家销售数据
 * @apiName statics
 * @apiGroup Admin-Statics
 *
 * @apiParam {ObjectId} _id 店铺id
 *
 * @apiSuccess {Object} day_orders 日订单量
 * @apiSuccess {Object} sales_valume  店铺销售额
 * @apiSuccess {Array} shop_sales  商品销售额分布
 */
// 查询所有商家销售数据
module.exports = async (req, res) => {
	// _id 店铺id
	let {
		_id
	} = req.query;
	// console.log(req.query);

	// 商品销售数据,日订单订单量,店铺销售额
	let shop_sales = [];
	let day_orders = [];
	let sales_valume = [];
	// 1.获取店铺所有的订单
	let sales = await Orders.find({
		order_store: _id,
		is_pay: true
	}).select('order_price order_goods order_store').populate({
		path: 'order_goods',
		model: Goods,
		select: 'goods_name goods_msg_price goods_cate',
		populate: {
			path: 'goods_cate',
			model: CategoryThree,
			select: 'title'
		}
	});
	sales.forEach(item => {
		console.log(item.order_goods)
		let index = shop_sales.findIndex(items => items._id === item.order_goods.goods_cate._id);
		if (index == -1) {
			shop_sales.push({
				_id: item.order_goods.goods_cate._id,
				value: item.order_price,
				name: item.order_goods.goods_cate.title,
			});
			return;
		}
		shop_sales[index].value += item.order_price
	})

	let week = [];
	let orders = [];
	let day_sales = [];
	// 2. 获取近七天每日订单量
	for (let i = 6; i >= 0; i--) {
		let nows = new Date();
		let last_day = nows.getFullYear() + '-' + formatDate(nows.getMonth() + 1) + '-' + formatDate(nows.getDate() - i);
		week.push(last_day);
		let order = await Orders.find({
			order_store: _id,
			is_pay: true,
			order_time: {
				$gte: new Date(new Date().setHours(0, 0, 0, 0) - 24 * 60 * 60 * 1000 * i),
				$lte: new Date(new Date().setHours(0, 0, 0, 0) + 24 * 60 * 60 * 1000 - 1 - 24 * 60 * 60 * 1000 * i)
			}
		})
		orders.push(order.length)
		let count = 0;
		// 3.1 获取日销售额
		order.forEach(item => {
			if (item) count += item.order_price;
		})
		day_sales.push(count);
		
	}
	// console.log(week, day_sales)

	// 3.2 周销售
	let week_sales = {
		xAxis: [],
		series: []
	};
	let week_begin = getCurrWeek();
	for(let i=0;i<7;i++) {
		week_begin.setDate(week_begin.getDate()+(i == 0 ? 0 : 1 ));
		let dates = week_begin.getFullYear() + '-' + formatDate(week_begin.getMonth() + 1) + '-' + formatDate(week_begin.getDate());
		week_sales.xAxis.push(dates);
		let order = await Orders.find({
			order_store: _id,
			is_pay: true,
			order_time: {
				$gte: new Date(new Date(getCurrWeek()).setHours(0, 0, 0, 0) ),
				$lte: new Date(new Date(week_begin).setHours(0, 0, 0, 0) + 24 * 60 * 60 * 1000 - 1)
			}
		})
		let count = 0;
		// 3.1 获取日销售额
		order.forEach(item => {
			if (item) count += item.order_price;
		})
		week_sales.series.push(count)
	}
	// console.log(week_sales)
	
	// 3.3 月销售
	let month_sales = {
		xAxis: [],
		series: []
	};
	let mongth_begin = getCurrentMonthBegin();
	let mongth_end = getCurrentMonthEnd();
	for(let i=0;i<mongth_end;i++) {
		mongth_begin.setDate(mongth_begin.getDate()+(i == 0 ? 0 : 1 ));
		let dates = mongth_begin.getFullYear() + '-' + formatDate(mongth_begin.getMonth() + 1) + '-' + formatDate(mongth_begin.getDate());
		month_sales.xAxis.push(dates);
		let order = await Orders.find({
			order_store: _id,
			is_pay: true,
			order_time: {
				$gte: new Date(new Date(getCurrentMonthBegin()).setHours(0, 0, 0, 0) ),
				$lte: new Date(new Date(mongth_begin).setHours(0, 0, 0, 0) + 24 * 60 * 60 * 1000 - 1)
			}
		})
		let count = 0;
		// 3.1 获取日销售额
		order.forEach(item => {
			if (item) count += item.order_price;
		})
		month_sales.series.push(count)
	}
	// console.log(month_sales)
	

	DataReturn.getData(res, 200, {
		shop_sales: shop_sales,
		day_orders: {
			xAxis: week,
			yAxis: orders
		},
		sales_valume: {
			xAxis: week,
			series: [day_sales, week_sales, month_sales]
		}
	}, '获取销售数据成功')

}
